package threadTest.CASTest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 功能描述: CAS: 乐观锁, 原子引用  version 或者时间戳
 * 2024/03/13
 * <p>
 * ZhangYi
 */
public class ABACASTest02 {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> stampedReference
                = new AtomicStampedReference<>(123,
                                               1);


        new Thread(()->{
            int stamp = stampedReference.getStamp();// 获得版本号/时间戳
            int value = stampedReference.getReference();
            if (stampedReference.compareAndSet(123, 124, stamp, stamp + 1)) {
                System.out.println("A1 执行+1");
            }
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 再次读取一次版本号
            System.out.println( "A1 修改变量后版本号为"+ stampedReference.getStamp());
            System.out.println( "A1 修改变量后的值为"+ stampedReference.getReference());

            if (stampedReference.compareAndSet(124,123,
                                               stampedReference.getStamp(),stampedReference.getStamp()+1)){
                System.out.println("复原成功" + stampedReference.getReference());
            }
        },"执行+1,然后再复原操作").start();

        new Thread(()->{
            int stamp = stampedReference.getStamp(); // 获取版本号
            Integer value = stampedReference.getReference();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (stampedReference.compareAndSet(123, 22, stamp, stamp + 1)) {
                System.out.println("A2 执行 +1");
            }
            System.out.println( "A2 修改变量后版本号为"+ stampedReference.getStamp());
            System.out.println( "A2 修改变量后的值为"+ stampedReference.getReference());


        }).start();
    }
}
